package sms

import (
	"net/http"
	"strings"
	"net/url"
	"time"
	"fmt"
	"crypto/md5"

	"io/ioutil"
	"encoding/json"
	"TanguyWeb/main/bean"
	"math/rand"
	"strconv"
	"TanguyWeb/main/config"
)

var dat map[string]interface{}

const codeNum = 6

func SendSms(phone string) (string, error) {
	code := ""
	for i := 0; i < codeNum; i++ {
		code += strconv.Itoa(rand.Intn(10))
	}
	timestamp := time.Now().Format("20060102150405")
	accountSid := "b2268a6b00054b9c880514687519dbcc"
	authToken := "f315053ebd3c48bc98078010fa935373"
	sig := fmt.Sprintf("%x", md5.Sum([]byte(accountSid+authToken+timestamp)))

	postValue := url.Values{
		"accountSid": {accountSid},
		"templateid": {"251513138"},
		"param":      {code},
		"to":         {phone},
		"timestamp":  {timestamp},
		"sig":        {sig},
	}

	postString := postValue.Encode()

	req, err := http.NewRequest("POST", "https://api.miaodiyun.com/20150822/industrySMS/sendSMS", strings.NewReader(postString))

	if err != nil {
		return "", err
	}
	req.Header.Set("Content-type", "application/x-www-form-urlencoded")
	client := &http.Client{}
	resp, err := client.Do(req)

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	json.Unmarshal(body, &dat)
	if v, ok := dat["respCode"]; ok {
		if v == "00000" {
			return code, nil
		} else {
			return "", bean.NewResultError(config.Err, "发送失败:错误码"+v.(string))
		}
	}
	return "", bean.NewResultError(config.Err, "发送失败")
}
func SendSmsDeBug(phone string) (string, error) {
	code := ""
	for i := 0; i < codeNum; i++ {
		code += strconv.Itoa(rand.Intn(10))
	}

	return code, nil
}
